﻿

var postApiUrl = '/api/WallPost/', commentApiUrl = '/api/Comment/';


// Model
function Post(data) {
  
    var self = this;
    data = data || {};
    self.PostId = data.PostId;
    self.Message = ko.observable(data.Message || "");
    self.PostedBy = data.PostedBy || "";
    self.PostedByName = data.PostedByName || "";
    self.PostedByAvatar = data.PostedByAvatar || "";
    self.LikeCount = data.LikeCount || "";
    self.PostedDate = getTimeAgo(data.PostedDate);
    self.error = ko.observable();
    self.PostComments = ko.observableArray();
    self.ShareDetail = ko.observable();
    self.newCommentMessage = ko.observable();
    self.Source = ko.observable();
    self.LinkThumbnailUrl = data.LinkThumbnailUrl;
    self.AlbumImage = data.AlbumImage;
    self.Groupid = data.Groupid;
    self.StatusHeader = data.StatusHeader;
    self.addComment = function () {
        var comment = new Comment();
        comment.PostId = self.PostId;
        comment.Message(self.newCommentMessage());
        return $.ajax({
            url: commentApiUrl,
            dataType: "json",
            contentType: "application/json",
            cache: false,
            type: 'POST',
            data: ko.toJSON(comment)
        })
       .done(function (result) {
           self.PostComments.push(new Comment(result));
           self.newCommentMessage('');
       })
       .fail(function () {
           error('unable to add post');
       });


    }
    if (data.PostComments) {
        var mappedPosts = $.map(data.PostComments, function (item) { return new Comment(item); });
        self.PostComments(mappedPosts);
    }
    self.toggleComment = function (item,event) {       
        $(event.target).next().find('.publishComment').toggle();
    }
    
    
}



function Comment(data) {
    var self = this;
    data = data || {};
  
    // Persisted properties
    self.CommentId = data.CommentId;
    self.PostId = data.PostId;
    self.Message = ko.observable(data.Message || "");
    self.CommentedBy = data.CommentedBy || "";
    self.CommentedByAvatar = data.CommentedByAvatar || "";
    self.CommentedByName = data.CommentedByName || "";
    self.CommentedDate = getTimeAgo(data.CommentedDate);
    self.error = ko.observable();
    //persist edits to real values on accept
    self.deleteComment = function() {

    };

}

function LikeCounter(data) {
    var self = this;
    data = data || {};

    // Persisted properties
   
    self.PostId = data.PostId;
    self.Message = ko.observable(data.Message || "");
    self.CommentedBy = data.CommentedBy || "";
    self.CommentedByAvatar = data.CommentedByAvatar || "";
    self.CommentedByName = data.CommentedByName || "";
    self.CommentedDate = getTimeAgo(data.CommentedDate);
    self.error = ko.observable();
    //persist edits to real values on accept
    self.deleteComment = function () {

    };

}

function getTimeAgo(varDate) {
    if (varDate) {
        return $.timeago(varDate.toString().slice(-1) == 'Z' ? varDate : varDate+'Z');
    }
    else {
        return '';
    }
}

function FeedSourceDetail() {
    this.Title = ko.observable();
    this.Body = ko.observable();
    this.ImageUrl = ko.observable();
    this.Source = ko.observable();
    this.Embed = ko.observable();
}

function PostViewModel() {
    this.Post = ko.observable();
    this.FeedSourceDetail = ko.observable();
}
var feedSourceDetail = "";
var source = "";
function viewModel() {
    var self = this;
    self.posts = ko.observableArray();
    self.newMessage = ko.observable();
    self.error = ko.observable();
    self.source = ko.observable();
   
    self.Source = ko.observable();
   
    self.loadPosts = function(postType) {
        //To load existing posts
        $.ajax({
            url: postApiUrl,
            dataType: "json",
            data:{postType:postType},
            contentType: "application/json",
            cache: false,
            type: 'GET'
        })
            .done(function(data) {
                var mappedPosts = $.map(data, function(item) { return new Post(item); });
                self.posts(mappedPosts);
              
                    $(".gallery-masonry").imagesLoaded(function () {
                        $(".gallery-masonry").masonry({
                            itemSelector: 'li',
                           
                            isAnimated: true
                        });
                    });
                    $(".colorbox-image").colorbox({
                        maxWidth: "90%",
                        maxHeight: "90%",
                        rel: $(this).attr("rel")
                    });
            })
            .fail(function() {
                error('unable to load posts');
            });
    };

    self.addPost = function () {
        //var feedSourceDetail = new FeedSourceDetail();
        //feedSourceDetail.Title = $("#Title").val();
        //feedSourceDetail.Body = $("#Body").val();
        
        var post = new Post();
        post.Message(self.newMessage());
        //post.Source(self.source());

        var postViewModel = new PostViewModel();
        postViewModel.Post = post;
        postViewModel.FeedSourceDetail = feedSourceDetail;
        postViewModel.Source = source;
        return $.ajax({
            url: postApiUrl,
            dataType: "json",
            contentType: "application/json",
            cache: false,
            type: 'POST',
            data: ko.toJSON(postViewModel)
        })
            .done(function (result) {
              
                self.posts.splice(0, 0, new Post(result));
                self.newMessage('');
                source = "";
                $("#preview-display").css('display', "none");
            })
            .fail(function() {
                error('unable to add post');
            });
    };

    self.addLike = function(data) {
        var like = new LikeData();
    };
    self.blurFunction = function(item, event) {
        var status = self.newMessage();
        var isUrl = ValidUrl(status);
        if (isUrl) {
            var url = "/Profile/StreamData?url=" + status;
            $.ajax({
                url: url,
                type: "POST",
                success: function(data) {
                    //alert(data);
                    $("#preview-display").css("display","block");
                    $("#preview-display").html(data.view);
                    var feedSourceDetailNew = new FeedSourceDetail();
                    feedSourceDetailNew.Embed = data.embed;
                    feedSourceDetailNew.Title = data.title;
                    feedSourceDetailNew.Body = data.body;
                    source = data.source;
                    feedSourceDetailNew.ImageUrl = data.image;
                  
                    feedSourceDetail = feedSourceDetailNew;
                    
                   // $("#Postsource").val("s");
                    $("#txtMessage").val("");
                },
                error: function(data){
                    alert("An error Occurred!!!");
                }
            });


        }
    };
   
    self.loadPosts(postType);
    return self;
   
};

//custom bindings

//textarea autosize
ko.bindingHandlers.jqAutoresize = {
    init: function (element, valueAccessor, aBA, vm) {
        if (!$(element).hasClass('msgTextArea')) {
            $(element).css('height', '1em');
        }
        $(element).autosize();
    }
};

ko.applyBindings(new viewModel());  

